package com.jianqiao.delivery.jnttrack.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jianqiao.delivery.util.HttpClientUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.jianqiao.delivery.jnttrack.entity.JntCancelEntity;
import com.jianqiao.delivery.jnttrack.entity.JntCreateEntity;
import com.jianqiao.delivery.jnttrack.entity.JntTrackEntity;
import com.jianqiao.delivery.jnttrack.entity.TariffCheckEntity;
import com.jianqiao.delivery.jnttrack.entity.vo.JntTrackResponseVo;
import com.jianqiao.delivery.jnttrack.service.JntTrackService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * author: cyx
 * create: 2024/8/12 18:11
 **/
@Service
@Slf4j
public class JntTrackServiceImpl implements JntTrackService {

    @Value("${jnt.track.username}")
    private String trackUsername;
    @Value("${jnt.track.key}")
    private String trackKey;
    @Value("${jnt.track.url}")
    private String trackUrl;

    @Value("${jnt.create.username}")
    private String createUsername;
    @Value("${jnt.create.apiKey}")
    private String createApikey;
    @Value("${jnt.create.key}")
    private String createKey;
    @Value("${jnt.create.url}")
    private String createUrl;

    @Value("${jnt.cancel.username}")
    private String cancelUsername;
    @Value("${jnt.cancel.apiKey}")
    private String cancelApikey;
    @Value("${jnt.cancel.key}")
    private String cancelKey;
    @Value("${jnt.cancel.url}")
    private String cancelUrl;

    @Value("${jnt.tariffCheck.customerName}")
    private String customerNameUsername;
    @Value("${jnt.tariffCheck.key}")
    private String customerNameKey;
    @Value("${jnt.tariffCheck.url}")
    private String customerNameUrl;

    @Override
    public List<JntTrackResponseVo> jnttrack(String awbNumber) {


        JntTrackEntity jntTrackEntity = new JntTrackEntity(awbNumber,"JIANQIAO");
        //将实体类转为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String bodyJsonStr="";
        try {
            bodyJsonStr = objectMapper.writeValueAsString(jntTrackEntity);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

//        String bodyJsonStr = JSONUtils.toJSONString(jntTrackEntity);
        //设置请求头
        Map<String ,String> headMap = new HashMap<>();
        headMap.put("Username" ,"JIANQIAO");
        headMap.put("Password" ,"aDVqZmLn53Pd");

        // Username and password
//        String username = "JIANQIAO";
//        String password = "aDVqZmLn53Pd";

        // Combine username and password
        String auth = trackUsername + ":" + trackKey;

        // Encode to Base64
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        headMap.put("Authorization" ,"Basic "+encodedAuth);

        //发起请求
        String response = HttpClientUtil.doPostJson(trackUrl, bodyJsonStr, headMap);
        String historyStr = JSONObject.parseObject(response).getString("history");
        ObjectMapper mapper = new ObjectMapper();
        List<JntTrackResponseVo> historyList = new ArrayList<>();
        try {
            historyList = mapper.readValue(historyStr, new TypeReference<List<JntTrackResponseVo>>() {
            });
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("响应response->" + response);
        return historyList;
    }

    @Override
    public String create(JntCreateEntity jntCreateEntity) {
        String string = UUID.randomUUID().toString().substring(0 ,7);
        //设置时间
        ZoneId zoneId = ZoneId.of("Asia/Bangkok");
        ZonedDateTime now = ZonedDateTime.now(zoneId);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = now.format(formatter);
        //设置参数
        jntCreateEntity.setOrderid("TEST-ORDER-" + string);
        jntCreateEntity.setUsername(createUsername);
        jntCreateEntity.setApi_key(createApikey);
        jntCreateEntity.setOrderdate(time);

        String jsonString = JSONObject.toJSONString(jntCreateEntity);

        String dataParam = "{\"detail\":[" + jsonString + "]}";
        String inputStr = dataParam + createKey;
        String dataSign = generateSignature(inputStr);

        System.out.println(dataParam);
        System.out.println(dataSign);
        //设置请求体
        List<NameValuePair> bodyList = new ArrayList<>();
        bodyList.add(new BasicNameValuePair("data_param", dataParam));
        bodyList.add(new BasicNameValuePair("data_sign", dataSign));

        //设置请求头
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type" ,"application/x-www-form-urlencoded");
        String response = HttpClientUtil.doPostJson(createUrl, bodyList);
        return response;
    }

    @Override
    public String cancel(JntCancelEntity jntCancelEntity) {
        //设置参数
        jntCancelEntity.setUsername(cancelUsername);
        jntCancelEntity.setApi_key(cancelApikey);

        String jsonString = JSONObject.toJSONString(jntCancelEntity);

        String dataParam = "{\"detail\":[" + jsonString + "]}";
        String inputStr = dataParam + cancelKey;
        String dataSign = generateSignature(inputStr);

        //设置请求体
        List<NameValuePair> bodyList = new ArrayList<>();
        bodyList.add(new BasicNameValuePair("data_param", dataParam));
        bodyList.add(new BasicNameValuePair("data_sign", dataSign));

        //设置请求头
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type" ,"application/x-www-form-urlencoded");
        String response = HttpClientUtil.doPostJson(cancelUrl, bodyList);
        return response;
    }

    @Override
    public String tariffCheck(TariffCheckEntity tariffCheckEntity) {
        //设置参数
        tariffCheckEntity.setCusName(customerNameUsername);

        String data = JSONObject.toJSONString(tariffCheckEntity);

        String inputStr = data + customerNameKey;
        String sign = generateSignature(inputStr);

        //设置请求体
        List<NameValuePair> bodyList = new ArrayList<>();
        bodyList.add(new BasicNameValuePair("data", data));
        bodyList.add(new BasicNameValuePair("sign", sign));

        //设置请求头
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type" ,"application/x-www-form-urlencoded");
        String response = HttpClientUtil.doPostJson(customerNameUrl, bodyList);

        return response;
    }

    public static String generateSignature(String inStr) {
        try {
            // 创建一个MessageDigest实例，初始化为MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算字符串的MD5散列值
            byte[] md5hash = md.digest(inStr.getBytes());
            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : md5hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            System.out.println("md5: " + hexString.toString());

            byte[] bytes = org.bouncycastle.util.encoders.Base64.encode(hexString.toString().getBytes());
            String encode = new String(bytes);
            System.out.println("encode = " + encode);

            return encode;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }
}
